<template>
	<div :class="{ counter: !isNumChange }" :style="nodeStyle" ref="counterRef"></div>
</template>
<script lang="ts" setup>
	import { delay, pxToRem } from '@/utils/common'
	import { ref, watch, onMounted } from 'vue'

	interface Props {
		nodeStyle?: string
		num: number
		fontSize?: number
	}
	const props = withDefaults(defineProps<Props>(), {
		nodeStyle: '',
		num: 0,
		fontSize: 16,
	})
	const isNumChange = ref(false)
	const initNum = ref(0)
	watch(
		() => props.num,
		async (_, oldVal) => {
			isNumChange.value = true
			initNum.value = oldVal
			await delay(50)
			isNumChange.value = false
		},
	)
	const counterRef = ref()
	onMounted(() => {
		counterRef.value.style.fontSize = pxToRem(props.fontSize!)
	})
</script>

<style lang="scss" scoped>
	@keyframes count {
		to {
			--t: v-bind(num);
		}
	}
	@property --t {
		syntax: '<integer>';
		inherits: false;
		initial-value: 0;
	}
	.counter::after {
		--t: v-bind(initNum);
		counter-reset: time var(--t);
		content: counter(time);
		animation: count 2s forwards, stop 1s step-end forwards;
	}
</style>
